/* $RCSFile: ModuleButton.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/ModuleButton.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Configuration;
using AddonNice.Design;
using AddonNice.Helpers;

using Trace2 =   System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{
	/// <summary>
	///  ModuleButton. Custom control for Module buttons ... derives from HtmlAnchor. 
	///  Allows text, image or both. Can be url hyperlink or postback button.
	///  Use ServerClick event to pick up on postback.
    /// Manage an internal skin name for its image when image is necessary
	/// </summary>
	[
	ToolboxData("<{0}:ModuleButton runat=server></{0}:ModuleButton>"),
	]
	public class ModuleButton : HtmlAnchor 
	{
        CtlLifeStatus LifeTSatus    =   CtlLifeStatus.Ctor;
        
        #region Enums
        /// <summary>
        /// Rendering options
        /// </summary>
        public enum RenderOptions : int
        {
            NotSet          =   -1,
            ImageOnly       =   0,
            ImageOnlyCSS    =   1,
            TextOnly        =   2,
            ImageAndTextCSS =   3

        }

        public enum CtlLifeStatus { Ctor,ChildCreate, Load, Prerender, Render, } // used to avoid setting skinID in Onload

        /// <summary>
        /// Group options
        /// </summary>
        public enum ButtonGroup : int
        {
            User            =   0,
            Admin           =   1,
            Custom          =   2
        }
        #endregion
        
        #region Constructor

        /// <summary>
		/// Ctor
		/// </summary>
		public ModuleButton()
		{
		}
		#endregion

		#region Events


        
        /// <summary>
		/// Init event handler.
		/// </summary>
		override protected void OnInit(EventArgs e)
		{
			EnableViewState = false;
			base.OnInit(e);
		}

        protected override void  CreateChildControls()
        {
            if ( ButtonTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton CreateChildControls BEG RenderAs:{0}", _renderAs),ButtonTraceSwitch.Sw.Info);
            LifeTSatus                 =    CtlLifeStatus.ChildCreate;
 	        base.CreateChildControls();
            if ( ButtonTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ModuleButton CreateChildControls END.",ButtonTraceSwitch.Sw.Info);
        }
		

        protected override void OnPreRender(EventArgs e)
        {
            if ( ButtonTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton OnPreRender BEG RenderAs:{0}", _renderAs),ButtonTraceSwitch.Sw.Info);
            LifeTSatus                 =    CtlLifeStatus.Prerender;
            PrepareChildControls();
            base.OnPreRender(e);
            if ( ButtonTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ModuleButton OnPreRender END.",ButtonTraceSwitch.Sw.Info);
        }
		
		/// <summary>
		/// Takes care of translating the inner text according the TranslationKey
        /// HtmlEncode the href text
        /// And render according the installed options for the module where this button is placed
        /// </summary>
        void PrepareChildControls()
		{
            if ( ButtonTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton PrepareChildControls RenderAs:{0}", _renderAs),ButtonTraceSwitch.Sw.Info);
			EnsureChildControls();
            LifeTSatus                  =    CtlLifeStatus.Load;
			if ( TranslationKey != string.Empty )
				InnerText               =   LocalizeHelper.Localize(TranslationKey, EnglishName);
			if ( InnerText == string.Empty )
				InnerText               =   EnglishName;
			HRef                        =   HttpContext.Current.Server.HtmlEncode(HRef);
            Title                       =   string.Concat(InnerText,"...");
			//Style.Add(HtmlTextWriterStyle.Display,"block");

			switch ( RenderAs )
			{
				case RenderOptions.TextOnly :
					Attributes.Add("class",CssClass);
					InnerHtml           =   string.Concat("<div class=\"btn-txt-only\">",InnerText,"</div>");
					if ( PopUp )
					{
						Attributes.Add("onclick",GetPopupCommand());
						Attributes.Add("target",Target);
						Attributes.Add("class",string.Concat(CssClass, " btn-is-popup btn-txt-only"));
					}
					else 
					    Attributes.Add("class",string.Concat(CssClass, " btn-txt-only"));
					break;

				case RenderOptions.ImageAndTextCSS :
					Style.Add(HtmlTextWriterStyle.BackgroundImage,string.Concat("url(",Image.ImageUrl,")"));
					Style.Add("background-repeat","no-repeat");
					Style.Add(HtmlTextWriterStyle.Height,Image.Height.ToString());
					Style.Add(HtmlTextWriterStyle.Width,Image.Width.ToString());
					InnerHtml               =   string.Concat("<div class=\"btn-img-txt\">",InnerText,"</div>");
					if ( PopUp )
					{
						Attributes.Add("onclick",GetPopupCommand());
						Attributes.Add("target",Target);
						Attributes.Add("class",string.Concat(CssClass, " btn-is-popup btn-img-txt"));
					}
					else 
						Attributes.Add("class",string.Concat(CssClass, " btn-img-txt"));

					break;

				case RenderOptions.ImageOnlyCSS :
					Style.Add(HtmlTextWriterStyle.BackgroundImage,string.Concat("url(",Image.ImageUrl,")"));
					Style.Add("background-repeat","no-repeat");
					Style.Add(HtmlTextWriterStyle.Height,Image.Height.ToString());
					Style.Add(HtmlTextWriterStyle.Width,Image.Width.ToString());
					InnerHtml                   =   string.Concat("<div class=\"btn-img-only-css\">",InnerText,"</div>");
					if ( PopUp )
					{
						Attributes.Add("onclick",GetPopupCommand());
						Attributes.Add("target",Target);
						Attributes.Add("class",string.Concat(CssClass, " btn-is-popup btn-img-only-css"));
					}
					else 
						Attributes.Add("class",string.Concat(CssClass, " btn-img-only-css"));
					break;

				case RenderOptions.ImageOnly :
				default :
					if ( PopUp )
					{
						Attributes.Add("onclick",GetPopupCommand());
						Attributes.Add("target",Target);
						Attributes.Add("class",string.Concat(CssClass, " btn-is-popup btn-img-only"));
					}
					else Attributes.Add("class",string.Concat(CssClass, " btn-img-only"));
					_image.BorderStyle          =   BorderStyle.None;
                    _image.AlternateText        =   string.Empty;
					_image.ToolTip              =   string.Empty;
					InnerText                   =   string.Empty;
                    if ( ButtonTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton OnLoad RenderAs ImageOnly image.SkinID:{0}", Image.SkinID),ButtonTraceSwitch.Sw.Info);
                    Controls.Add(Image);
					break;
			}
		}

        /// <summary>
		/// Load event handler: take care of translating the inner text according the TranslationKey
        /// HtmlEncode the href text
        /// And render according the installed options for the module where this button is placed
		/// </summary>
		protected override void OnLoad(EventArgs e)
		{
            if ( ButtonTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton OnLoad RenderAs:{0}", _renderAs),ButtonTraceSwitch.Sw.Info);
			base.OnLoad(e);
		}

		/// <summary>
		/// Builds Javascript popup command
		/// </summary>
		protected string GetPopupCommand()
		{
            string gPath        =   Path.ToAbsolute(Config.PortalScriptsPath+"/popup.js");
            if ( Page is ADNPage )
            {
                ((ADNPage)Page).RegisterADNClientScriptInclude("adn_popup", gPath);
            }
            else
            {
			    Type cs	            =	Page.GetType();
                // make sure the popup script is registered
                Page.ClientScript.RegisterClientScriptInclude(cs, "adn_popup", gPath);
            }

			// build the popup command
			StringBuilder sb    =   new StringBuilder();
			sb.Append("link_popup(this");
			if ( !string.IsNullOrEmpty(PopUpOptions) )
			{
				sb.AppendFormat(", '{0}'",PopUpOptions);
			}
			sb.Append(");return false;");

			return sb.ToString();
		}

		#endregion

		#region Properties

		private bool _popUp = false;
		public bool PopUp
		{
			get{return _popUp;}
			set{_popUp = value;}
		}

        /// <summary>
        /// default popup options
        /// </summary>
		private string _popUpOptions = "toolbar=1,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=800,height=600,screenX=15,screenY=15,top=15,left=15";
        public string PopUpOptions
		{
			get{return _popUpOptions;}
			set{_popUpOptions = value;}
		}

		private string _name = string.Empty;
		/// <summary>
		/// Hides inherited Name
		/// </summary>
		new private string Name
		{
			get{return _name;}
			set{_name = value;}
		}

		private string cssClass = "adn_mod_btn";
		/// <summary>
		/// Sets CSS Class on control
		/// </summary>
		public string CssClass
		{
			get{return cssClass;}
			set{cssClass = value;}
		}

		private ButtonGroup group = ButtonGroup.User;
		/// <summary>
		/// Holds Button group enum: User, Admin or Custom
		/// </summary>
		public ButtonGroup Group
		{
			get{return group;}
			set{group = value;}
		}

		private Image _image = new Image();
		/// <summary>
		/// Button image take the internal skin for it or the parent skinid
		/// </summary>
		public Image Image
		{
			get
            {
                if ( ( LifeTSatus <    CtlLifeStatus.Load ) && 
                    string.IsNullOrEmpty(_image.SkinID) && !string.IsNullOrEmpty(ImageSkin))
                    _image.SkinID = ImageSkin;
                if ( ButtonTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton Image.SkinID:{0}", _image.SkinID),ButtonTraceSwitch.Sw.Info);
                return _image;
            }
		}

		private string translation = string.Empty;
		/// <summary>
		/// translation
		/// </summary>
		public string EnglishName
		{
			get{return translation;}
			set{translation = value;}
		}
		
		private string _translationKey = string.Empty;
		/// <summary>
		/// translation key
		/// </summary>
		public string TranslationKey
		{
			get{return _translationKey;}
			set{_translationKey = value;}
		}

		private RenderOptions _renderAs = RenderOptions.ImageOnly;
		/// <summary>
		/// Active RenderAs option
		/// </summary>
		public RenderOptions RenderAs
		{
			get{return _renderAs;}
			set{_renderAs = value;}
		}

        private string _ImageSkin = string.Empty;
        /// <summary>
        /// Active RenderAs option
        /// </summary>
        public string ImageSkin
        {
            get
            {
                if ( ButtonTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton Get ImageSkin:{0}", _ImageSkin),ButtonTraceSwitch.Sw.Info);
                return _ImageSkin;
 
            }
            set
            {
                _ImageSkin = value;
                if ( ButtonTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton Set ImageSkin:{0}", _ImageSkin),ButtonTraceSwitch.Sw.Info);
                if (( LifeTSatus < CtlLifeStatus.Load ) &&  string.IsNullOrEmpty(_image.SkinID))
                {
                    _image.SkinID = _ImageSkin;
                    if ( ButtonTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleButton Image Set Skin:{0}", _image.SkinID),ButtonTraceSwitch.Sw.Info);
                }
            }
        }
        #endregion
	}
}
